package com.security.demo;


import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;


public class RSAUtils {

    /**
     * 转公钥
     *
     * @param keyStr 公钥数据字符串
     */
    public static RSAPublicKey toPublicKey(String keyStr) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64Utils.decode(keyStr));
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }


    /**
     * 加密
     *
     * @param data 明文数据
     */
    public static String encrypt(String data, String keysrc) {
        RSAPublicKey key = null;
        Cipher cipher = null;
        byte[] bytes = new byte[0];
        try {
            key = RSAUtils.toPublicKey(keysrc);
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            bytes = cipher.doFinal(data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return URLEncoder.encode(Base64Utils.encode(bytes));
    }
}
